package cn.corgy.registry;


import cn.corgy.dto.RpcRequest;
import cn.corgy.extension.SPI;
import cn.corgy.module.loadbalance.LoadBalance;
import org.slf4j.Logger;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * 服务发现
 */
@SPI
public interface ServiceDiscovery {
    /**
     * 通过rpcServiceName查找服务
     *
     * @param rpcRequest 请求信息实体
     * @return 服务地址
     */
    InetSocketAddress lookupService(RpcRequest rpcRequest);

    default InetSocketAddress getInetSocketAddress(RpcRequest rpcRequest, List<String> list, LoadBalance loadBalance, Logger log) {
        String targetServiceUrl = loadBalance.selectServiceAddress(list, rpcRequest);
        log.info("成功找到服务地址: [{}]", targetServiceUrl);
        String[] socketAddressArray = targetServiceUrl.split(":");
        String host = socketAddressArray[0];
        int port = Integer.parseInt(socketAddressArray[1]);
        return new InetSocketAddress(host, port);
    }
}
